var RNFS = require('react-native-fs');
import RNFileSelector from 'react-native-file-selector';
import React, { Component } from 'react';
import FileUtil from '../../../../utils/file'
import { headers, data } from '../json'
import XLSX from 'xlsx';
import { Modal, View, Text, TextInput, TouchableHighlight, StyleSheet, Image, ImageBackground, TouchableOpacity, PermissionsAndroid, Alert, Pressable,ToastAndroid,Platform,Dimensions
} from 'react-native'
import { color } from 'react-native-reanimated';
import { changeloginStatus, getexam } from '../../../../actions/actionCreators'
import store from '../../../../store/configureStore'
import { examinationpath } from '../../../../utils/path'
import  RNPop from './model'
let screenWidth = Dimensions.get('window').width;
let screenHeight = Dimensions.get('window').height;
class Tikumodel extends Component {
    constructor(props) {
        super(props);
        this.state = {
            title: '',
            examname: '',
            path: "选择文件",
            danxuan: '',
            duoxuan: '',
            panduan: '',
            Allcount: '',
            picturepath: '',
            staus: 1,//默认开放
            fmModalVisible: false,
            images: [],
            imgindex: 1,
            pagesize: 10,
            pageindex: 0,

        }
        this.readFile()
        console.log(121212, props,12)
    }
    readFile = () => {
        // 但是在后来的设备中，很多中高端机器都将自己的机身存储扩展到了8G以上，他们将存储在概念上分成了"内部存储internal【一般在data/data/包名/ 下的文件】" 和"外部存储external，包括外置sd卡和内置sd卡【 / sd卡根目录/Android/data/<包名>/ 下的文件，不同机型具体路径有差异】" 两部分，但其实都在手机内部。
        // 获取内置sd卡（手机自带的属于外部存储部分）这个目录下存在的文件路径 RNFS.readDir('/storage/emulated/0')也可以，其中/storage/emulated/0目录就是机身存储的外部存储路径【https://blog.csdn.net/csdn_aiyang/article/details/80665185】
        console.log(RNFS.ExternalStorageDirectoryPath)
        //ExternalStorageDirectoryPath 读取外部储蓄内存目录是获取外部存储的根路径 【可能包括机身外部存储和和插入sd卡路径】
        RNFS.readDir(RNFS.ExternalStorageDirectoryPath) // On Android, use "RNFS.DocumentDirectoryPath（内置存储）" (MainBundlePath is not defined)
            .then((result) => {
                console.log('GOT RESULT', result);
                // stat the first file
                return Promise.all([RNFS.stat(result[0].path), result[0].path]);
            })
            .then((statResult) => {
                if (statResult[0].isFile()) {
                    // if we have a file, read it
                    return RNFS.readFile(statResult[1], 'utf8');
                }
                return 'no file';
            })
            .then((contents) => {
                // log the file contents
                console.log(contents);
            })
            .catch((err) => {
                console.log(err.message, err.code);
            });

    }
    _uploadFile = (path) => {
        const formData = new FormData();
        const file = {
            uri: path,
            type: 'multipart/form-data;charset=utf-8',
            // name: image.name,
            // size: image.size,
        };
        formData.append('file', file);
        fetch('http://192.168.0.183:8080/whale/test/upload_files', {
            method: 'POST',
            headers: {
                'Content-Type': 'multipart/form-data',
            },
            body: formData,
        })
            .then((response) => response.text())
    }
    // 是否具有权限
    requestCameraPermission = async () => {
        try {
            const granted = await PermissionsAndroid.request(
                PermissionsAndroid.PERMISSIONS.CAMERA,
                {
                    title: "Cool Photo App Camera Permission",
                    message:
                        "Cool Photo App needs access to your camera " +
                        "so you can take awesome pictures.",
                    buttonNeutral: "Ask Me Later",
                    buttonNegative: "Cancel",
                    buttonPositive: "OK"
                }
            );
            if (granted === PermissionsAndroid.RESULTS.GRANTED) {
                console.log("You can use the camera");
            } else {
                console.log("Camera permission denied");
            }

        } catch (err) {
            console.warn(err);
        }
    };

    /*读取文件*/
    getfile = () => {
        RNFileSelector.Show(
            // 外部存储卡的数据内容复制到安卓内置内存的某个文件夹
            {
                // path:'/data/user/0/com.awesomeproject/',//可以自定义路径
                path: '/storage/',//可以自定义路径
                title: '请选择文件',
                onDone: async (path) => {
                    var index = path.lastIndexOf("."); // lastIndexOf("/")  找到最后一个  /  的位置
                    var fileType = path.substr(index + 1); // substr() 截取剩余的字符，即文件名doc
                    if (fileType!=='xlsx' && fileType!=='xls') {
                        ToastAndroid.showWithGravity('请选择后缀名为xlsx或者xls的excel文件',ToastAndroid.SHORT,
                        ToastAndroid.CENTER)  
                        return
                    }
                
                    RNFS.readFile(path, 'ascii').then(res => {
                        const workbook = XLSX.read(res, { type: 'binary' });
                        console.log(workbook)
                        // 读取到保存的excel新文件进行修改字段操作
                        var worksheet = workbook.Sheets[workbook.SheetNames[0]];
                        var jsondata = XLSX.utils.sheet_to_json(worksheet);
                        const sliceArr = jsondata.slice(3)
                        console.log(jsondata,sliceArr)
                        let danxuan = 0
                        let duoxuan = 0
                        let panduan = 0
                        sliceArr.map((item,index) => {
                            // 每个数据都会执行下面代码|| !item['score_']，分数总分100分，是写死的所以这要删掉，按照出题数量得平均分
                            if (!item['answer'] || !item['content'] || !item['content_1'] || !item['content_2'] || !item['order']  || !item['topic_type']) {
                                // 如果·有一个为空，后面不执行，提示答题表信息不完整，请参照模板
                                let rnPop = this.refs.rnPop
                                console.log(444444,item)
                                rnPop.show({content:`答题表题号为${index+1}数据不完整，请参照模板填入必填字段`,btns:[
                                    {
                                        text: '确定',
                                        style: {color: '#30a4fc'},
                                        onPress() {
                                            rnPop.close();
                                        }
                                    }
                                    
                                ]})
                                // Alert.alert('提示', '答题表信息不完整，请参照模板填入必填字段', [
                                //     {
                                //         text: '取消',
                                //         onPress: () => console.log('Cancel Pressed'),
                                //         style: 'cancel'
                                //     },
                                //     { text: '确定', onPress: () => console.log('OK Pressed') },

                                // ]);
                            } else {
                                // 统计单选题，多选题,文件名，同时把名字作为标题 把path路径存在state
                                var filename = path.substring(path.lastIndexOf('/'))
                                var name = filename.split('.')[0].split('/')[1]
                                this.setState({ path: path, title: name, examname: name })
                                if (item.topic_type-0 == 1) {
                                    danxuan += 1
                                } else if (item.topic_type-0 == 2) {
                                    duoxuan += 1

                                } else if (item.topic_type-0 == 3) {
                                    panduan += 1
                                }
                            }
                        })
                        console.log(sliceArr)
                        console.log(danxuan, duoxuan)
                        this.setState({ danxuan: danxuan, duoxuan: duoxuan, panduan: panduan, Allcount: sliceArr.length })

                    })

                },
                onCancel: () => {
                    console.log('cancelled')
                }
            })

    }
    copyexam = async (importitem) => {
        let rnPop = this.refs.rnPop

        // 没有选择文件和标题就返回
        if (!this.state.path || !this.state.title) {
            let rnPop = this.refs.rnPop
            rnPop.show({content:"没有选择文件或者填写标题",btns:[
                {
                    text: '确定',
                    style: {color: '#30a4fc'},
                    onPress() {
                    }
                }
                
            ]})
            // Alert.alert('提示', '没有选择文件或者填写标题', [
            //     {
            //         text: '取消',
            //         onPress: () => console.log('Cancel Pressed'),
            //         style: 'cancel'
            //     },
            //     { text: '确定', onPress: () => console.log('OK Pressed') },

            // ]);
            return;
            // 把原来的路径文件删了。更新这个id数据的所有内容

        }
        // 如果有封面路径，把封面路径也加了，封面是固定手动放在一个文件夹下面
        let path = this.state.path
        let filePath = RNFS.ExternalDirectoryPath + '/AnsweringMachine/examination'//excel数据库                   
        const isExists = await FileUtil.isExistFile(filePath);
        // const isExists1 = await FileUtil.isExistFile( RNFS.DocumentDirectoryPath);
        // console.log(isExists,isExists1)//false true
        if (isExists) {//特定目录【/data/user/0/com.awesomeproject/files】下存在某个【AnsweringMachine】文件夹，没有就创建这个文件夹，有就查询这个文件下是否已存在即将复制的文件名，防止重合
            // 如果存在看看path路径是否在excel文件下存在，不存在就开始复制，存在就提醒姨存在
            //切割路径的最后一个文件名获取到这个excel文件名
            var filename = path.substring(path.lastIndexOf('/'))
            const fileisExists = await FileUtil.isExistFile(filePath + filename);//看选中的文件名是否存在数据库的文件
            console.log(fileisExists)
            if (fileisExists) {//判断特定目录【/data/user/0/com.awesomeproject/files/AnsweringMachine】存在文件夹有没有这个【demo.xlsx】文件，没有就复制，有就不复制
                rnPop.show({content:"该文件名已经在库里存在，请重新选择",btns:[
                    {
                        text: '确定',
                        style: {color: '#30a4fc'},
                        onPress() {
                        }
                    }
                    
                ]})
                RNFS.readDir(filePath) // On Android, use "RNFS.DocumentDirectoryPath" (MainBundlePath is not defined)
                    .then((result) => {
                        console.log('已存在文件', result);
                        // stat the first file
                        return Promise.all([RNFS.stat(result[0].path), result[0].path]);
                    })

            } else {
                // const granted = await PermissionsAndroid.requestMultiple([ PermissionsAndroid.PERMISSIONS.READ_EXTERNAL_STORAGE, PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE])//granted返回的权限，granted代表通过权限，
                //  PermissionsAndroid.check(PermissionsAndroid.PERMISSIONS.READ_EXTERNAL_STORAGE).then(res=>{
                //     console.log(res,23232)//为false 表示没有权限denied代表不通过权限，还需要到AndroidManifest.xml配置
                // }).catch(e=>{
                //     console.log(e,232323)
                // })
                // console.log(PermissionsAndroid.RESULTS,granted)
                // const destPath =  RNFS.DocumentDirectoryPath + '/test.txt';//把sd卡的/storage/emulated/0/Download/功能.txt复制到/data/user/0/com.awesomeproject/files/test.txt
                // RNFS.copyFile('/storage/emulated/0/Download/功能.txt', '/data/user/0/com.awesomeproject/files/test.txt' )
                // 注意copy的俩参数路径要具体到文件的路径，而不是文件夹，而且文件类型【.txt/.xlsx】是一致的
                // 判断数据对不对在复制xlsx文件到指定文件夹
                let userpath = RNFS.ExternalDirectoryPath + '/AnsweringMachine/mysqle/examination.txt'
                let currentid;
                RNFS.copyFile(path, filePath + filename).then(res => {
                    // 复制成功要要解析当前excel获得相关数据在在examination.txt里面记录数据
                    console.log(res)
                    RNFS.readFile(userpath, 'utf8').then(res => {
                        console.log(res)
                        var arr = JSON.parse(res)
                        // 如果是编辑需要把原来的路径删掉
                        if (importitem) {
                            currentid = importitem.id
                        } else {
                            // 这样可能id会重合
                            if (arr.length < 1) {
                                currentid = 1
                            } else {
                                currentid = arr[arr.length - 1].id + 1
                            }

                        }
                        var obj = { id: currentid, title: this.state.title, picturepath: this.state.picturepath, staus: this.state.staus, Allcount: this.state.Allcount, danxuan: this.state.danxuan, duoxuan: this.state.duoxuan, panduan: this.state.panduan, examname: this.state.examname, exampath: filePath + filename, sort: currentid }
                        // staus默认1,开启，同时判断text数据是不是空，是空id=1,不是空，排在最后一个
                        if (!importitem) {
                            arr.push(obj)
                        } else {
                            // 如果是编辑替换就删除替换数据
                            let index1
                            arr.map((item, index) => {
                                if (item.id == importitem.id) {
                                    index1 = index
                                }
                            })
                            arr.splice(index1, 1, obj)
                            console.log(arr)
                        }

                        console.log(arr, obj, currentid)
                        RNFS.writeFile(userpath, JSON.stringify(arr), 'utf8')
                            .then((success) => {
                                console.log('FILE WRITTEN!');
                                ToastAndroid.showWithGravity('保存文件成功',ToastAndroid.SHORT,
                                ToastAndroid.CENTER)
                                var action = getexam()
                                store.dispatch(action)//刷新
                                this.props.handtimucloseVisible(false)

                            })
                            .catch((err) => {
                                console.log(err.message);
                            })


                    })



                }).catch(e => {
                    console.log(e)
                })
            }

        } else {
            //不存在就创建目录并且复制第一个excel文件到这个文件夹当中
            RNFS.mkdir(filePath).then((res) => {
                console.log(res, FileUtil.isExistFile(filePath), 11111)

            })

        };
    }
    readexamfile = (value) => {
        // 写入文件
        RNFS.writeFile(examinationpath, JSON.stringify(value), 'utf8')
            .then((success) => {
                console.log('FILE WRITTEN!');
                let rnPop = this.refs.rnPop
                rnPop.show({content:"操作成功",btns:[
                    {
                        text: '确定',
                        style: {color: '#30a4fc'},
                        onPress() {
                        }
                    }
                    
                ]})
                var action = getexam()
                store.dispatch(action)


            })
            .catch((err) => {
                console.log(err.message);
            })


    }
    changeexam = async () => {
        // 当编辑的时候虽然title是props初始化复制的，但是改变title不会改变props本身原来的值//改变数据库的路径，标题，封面路径，删除原来的题库加入新的题库,用户可能只是修改题库的封面，如果没选路径，还是数据库的路径excel文件只改封面，删除了这个文件就没办法复制了,copyflie应该是覆盖原来的
        console.log(this.state.title, this.state.path, this.props)
        if (this.state.path == this.props.importitem.exampath) {
            // Alert.alert('提示', '当前没有新题库重载，请选着需要重载的题库', [
            //     { text: '确定', onPress: () => console.log('OK Pressed') },

            // ]);
            // return;
        // 可以修改标题和名字
          // 修改标题
          var obj = Object.assign(this.props.importitem, {title: this.state.title, picturepath: this.state.picturepath, })
          console.log(obj)
          let index1
          var arr = store.getState().getexams
  
          arr.map((item, index) => {
              if (item.id == this.props.importitem.id) {
                  index1 = index
              }
          })
          arr[index1] =obj
          console.log(JSON.stringify(arr))//已更新
          //更新下最新数据在写入
          this.readexamfile(arr)

        }else{
            // 先删除改路径下的excel答题文件
            // 开始重载，更新表
            const fileisExists = await FileUtil.isExistFile(this.props.importitem.exampath)
            if(fileisExists){//防止测试几个题库共用一个excel表，第一个答题卡删掉替换了了excel表，第二个就找不到这个共用的表走catch
                RNFS.unlink(this.props.importitem.exampath)
                .then(() => {
                    this.copyexam(this.props.importitem)
                })
                .catch((err) => {
                    console.log(err.message);
                })
        
            }else{
                this.copyexam(this.props.importitem)
            }
            console.log(this.props.importitem.exampath)
      
        }
        
        

    }
    demogetfile = () => {
        // let that = this
        //    this._uploadFile=_uploadFile(path)
        RNFileSelector.Show(
            // 外部存储卡的数据内容复制到内部某个文件夹
            {
                title: '请选择文件',
                onDone: (path) => {
                    // this.state.path = path
                    console.log(path)
                    // 以下功能全为测试是否新建excel，改写excel文件功能
                    //  1，RNFS.readFile(path,'utf8')读取utf8编码的text文件
                    //  2，读取excel
                    RNFS.readFile(path, 'ascii').then(res => {
                        //一 读取某个文件夹excel文件获取到数据 
                        const workbook = XLSX.read(res, { type: 'binary' });
                        console.log(workbook)

                        //二，新建一个exce文件并且填充数据和修改一个excel文件的数据
                        var aoa = [['id', '姓名', '性别', '年龄', '注册时间'], [1, '张三', '男', 18, new Date()], [2, '李四', '女', 22, new Date()]];
                        var sheet = XLSX.utils.aoa_to_sheet(aoa);
                        var new_workbook = XLSX.utils.book_new();//创建虚拟的workbook
                        XLSX.utils.book_append_sheet(new_workbook, sheet, "SheetJS");//把sheet添加到workbook里，向工作簿当中追加一个工作表
                        console.log(new_workbook)

                        // 写入excel分为2种，一种是基于现有excel修改，一种是全新生成
                        const wbout = XLSX.write(new_workbook, { type: 'binary', bookType: "xlsx" });
                        // openDownloadDialog(sheet2blob(sheet),'导出.xlsx');

                        console.log(wbout, sheet, path)
                        // 下面操作是在app安卓系统全新生成一个xlsx文件并且把wbout内容填充到excel里面
                        let paths = RNFS.DocumentDirectoryPath + '/demo1.xlsx';//自动手动拼接一个文件夹路径也可以是txt文件
                        // let paths = '/storage/emulated/0/Download/' + 'demo1.xlsx';//安卓表示这个路径权限不够，不可读写操作文件否则报错
                        // 使用ExternalStorageDirectoryPath=/storage/emulated/0时，需要请求权限（在Android上）才能读取和写入外部存储；在Android23版本以后需要申请权限；申请权限示例：https://facebook.github.io/react-native/docs/permissionsandroid
                        RNFS.writeFile(paths, wbout, 'ascii').then((success) => {
                            //三， 以上表示在某个特定绝对路径新建excel并且填充数据成功，下面可以读取到这个路径的excel文件。测试是否可以修改工作表
                            console.log(success, 999999999)
                            RNFS.readFile(paths, 'ascii').then(res => {
                                console.log(res)
                                const workbook = XLSX.read(res, { type: 'binary' });
                                console.log(workbook)
                                // 读取到保存的excel新文件进行修改字段操作
                                var worksheet = workbook.Sheets[workbook.SheetNames[0]];
                                var jsondata = XLSX.utils.sheet_to_json(worksheet);
                                console.log(jsondata)
                                jsondata[1]['姓名'] = "李四修改1次"//实际上就是定义的worbook改掉了
                                let changeworksheet = XLSX.utils.json_to_sheet(jsondata)
                                // 转化为json数据修改excel数据后重新写入工作表
                                workbook.Sheets[workbook.SheetNames[0]] = changeworksheet
                                const wbout = XLSX.write(workbook, { type: 'binary', bookType: "xlsx" });
                                RNFS.writeFile(paths, wbout, 'ascii').then((r) => {/* :) */ }).catch((e) => {/* :( */ });
                                console.log(worksheet, workbook)
                            })
                        }).catch((e) => {
                            console.log(e, 999999999)

                        });
                    });


                    // this._uploadFile('file://' + path) // 根据官方给的fetch方法封装的上传方法
                },
                onCancel: () => {
                    console.log('cancelled')
                }
            }
        )
    }
    onChangeText = (val) => {
        console.log(1111)
        this.setState({ title: val })
    }
    choosefm = async () => {
        // 把内存卡某个路径下的图片文件夹的目录复制到另一个文件夹[后面可以去掉这个操作，直接手动复制到特定文件夹就行了]
        // let destPath =  RNFS.ExternalDirectoryPath + '/AnsweringMachine/Images/examinationpicture/10.png'//excel数据库                   
        // RNFS.copyFile('/storage/emulated/0/Download/10.png', destPath)
        // .then(() => {
        //     console.log('copyFIle Success');
        // })
        // .catch((err) => {
        //     console.log('copyFile failed', err);
        // });
        this.setState({ fmModalVisible: true })
        // 读取特定文件下封面的图片,如果已经加入题库表路径的图片被人工删除的话显示卡片可能因为找不到图片报错，验证后不显示找不到的图片，不影响
        let imagespath = RNFS.ExternalDirectoryPath + '/AnsweringMachine/Images/examinationpicture'
        RNFS.readDir(imagespath) // On Android, use "RNFS.DocumentDirectoryPath（内置存储）" (MainBundlePath is not defined)
            .then((result) => {
                console.log('GOT RESULT', result);
                result.unshift({ mtime: 1 })
                this.setState({ images: result })
                // stat the first file
            })
       

    }
    _onPressButton(val, item) {
        let path = item ? item.path : ''
        this.setState({ imgindex: val + 1, picturepath: path })
        console.log(val, item)
    }
    onPressFunction = () => {
        this.setState({ fmModalVisible: false })


    }
    onPresspre = () => {
        console.log(11)
        if (this.state.pageindex > 0) {
            this.setState({ pageindex: this.state.pageindex - 1 })
        } else {
            ToastAndroid.showWithGravity('已是第一页',ToastAndroid.SHORT,
            ToastAndroid.CENTER)  
        }
    };
    onPressnext = () => {
        let pageMax = Math.ceil(this.state.images.length / this.state.pagesize)
        console.log(this.state.pageindex, pageMax)
        if (this.state.pageindex + 1 < pageMax) {
            this.setState({ pageindex: this.state.pageindex + 1 })
            // 即使这增加了1 渲染的时候还说拿到前一次的pageindex.不及时更新数据
        } else {
            ToastAndroid.showWithGravity('已是最后一页',ToastAndroid.SHORT,
            ToastAndroid.CENTER)  
        }

    };
    UNSAFE_componentWillReceiveProps(nextProps) {
        // 这个生命周期在熏染之后才执行无效，不能在render或者componentWillMount周期改变state会导致无限循环，因为只要数据改变就会第二次循环，第二次有改，无限循环下午
        var obj = nextProps.importitem
        if (obj) {
            this.setState({ picturepath: obj.picturepath, title: obj.title, examname: obj.examname, path: obj.exampath, danxuan: obj.danxuan, duoxuan: obj.duoxuan, panduan: obj.panduan, Allcount: obj.Allcount, staus: obj.staus, sort: obj.sort })
            console.log(99999999999999, nextProps, this.props.importitem, this.state.title)
        }else{
            this.setState({ path: '', title: ''})
        }
     

    }
    onLayout = event => {
        //获取根View的宽高
        let { width, height } = event.nativeEvent.layout;
        console.log("通过onLayout得到的宽度：" + width);
        console.log("通过onLayout得到的高度：" + height);
    
        // 一般设备横屏下都是宽大于高，这里可以用这个来判断横竖屏
        let isLandscape = width > height;
        if (isLandscape) {
          this.setState({
            videoWidth: width,
            videoHeight: height,
          });
        } else {
          this.setState({
            videoWidth: width,
            videoHeight: (width * 9) / 16,
          });
        }
        // Orientation.unlockAllOrientations();
      };
    render() {

        var newarrimg = this.state.images.slice(this.state.pageindex * this.state.pagesize, (this.state.pageindex + 1) * this.state.pagesize);
        console.log(newarrimg)
      
        return (
            <Modal
                animationType="slide"
                transparent={true}
                // 继承属性和方法
                visible={this.props.tikumodalVisible}
                onRequestClose={() => {
                    Alert.alert("Modal has been closed.");
                }}
            >
                   <RNPop ref="rnPop" />
                <View style={styles.centeredView} onLayout={this.onLayout}>
                    <ImageBackground style={{ ...styles.modalView }}
                        source={require('../../../../../assets/imgs/a1/background.png')}
                        imageStyle={{ resizeMode: 'stretch' }}

                    >
                        <Text style={styles.modalText} >{this.props.importitem ? '重载更新题库' : '导入新题库'}</Text>
                        <Pressable style={{ position: "absolute", right: 10, top: 5,zIndex:100, }} onPress={() => { this.props.handtimucloseVisible(false) }}><Image
                            style={{ width: 40, height: 40 }}
                            source={require('../../../../../assets/imgs/close.png')}

                        /></Pressable >

                        <View style={styles.contaner}>
                            <View style={styles.contanerleft}>

                                <ImageBackground style={styles.tinyLogo}
                                    source={{ uri: `file://${this.state.picturepath}` }}
                                >
                                   <View style={styles.shawdows}>
                               
                                        <Text style={{ textAlign: "center", color: "#fff" }}>{this.state.title || '标题'}</Text>
                                        <View style={{marginTop:10}}>
                                        <Text style={{ color: "#fff", fontSize: 10 }} >单选题:{this.state.danxuan}</Text>
                                        <Text style={{ color: "#fff", fontSize: 10 }} >多选题:{this.state.duoxuan}</Text>
                                        <Text style={{ color: "#fff", fontSize: 10 }} >判断题:{this.state.panduan}</Text>
                                  
                                    </View>
                                   
                                   </View>

                                </ImageBackground>



                            </View>
                            <View style={styles.contanerright}>
                                <TouchableHighlight
                                    style={{ ...styles.chooseButton }}
                                // onPress={this.login}
                                >
                                    <Text style={styles.textStyle} onPress={() => { this.getfile() }} numberOfLines={5}>{this.state.path}</Text>
                                </TouchableHighlight>
                                <TextInput
                                    style={{ height: 40, borderColor: '#62AEDD', backgroundColor: "#3070AF", borderWidth: 1, color: "#fff" }}
                                    onChangeText={text => this.onChangeText(text)}
                                    value={this.state.title}
                                    clearButtonMode='while-editing'
                                    selectionColor="black"
                                />
                                <TouchableHighlight
                                    style={{ ...styles.fmButton }}
                                // onPress={this.login}
                                >
                                    <Text style={styles.textStyle} onPress={() => { this.choosefm() }}>封面设置</Text>

                                </TouchableHighlight>
                                <Modal
                                    animationType="slide"
                                    transparent={true}
                                    // 继承属性和方法
                                    visible={this.state.fmModalVisible}
                                    onRequestClose={() => {
                                        Alert.alert("Modal has been closed.");
                                    }}
                                >
                                   <View style={{  
        flexDirection:"row",
        justifyContent: "center",
        alignItems: "center",
        height:'100%',
        // backgroundColor:"#fff"
        
        }}>
                                   <ImageBackground style={{ ...styles.modalView1, width:this.state.videoWidth }}
                                        source={require('../../../../../assets/imgs/a1/background.png')}
                                        imageStyle={{ resizeMode: 'stretch' }}

                                    >
                                        <Text style={{ color: "#fff" }}>封面选择</Text>
                                        <Pressable style={{ position: "absolute", right: 20, top: 30,zIndex:100, }} onPress={() => { this.setState({ fmModalVisible: false }) }}><Image
                                            style={{ width: 40, height: 40 }}
                                            source={require('../../../../../assets/imgs/close.png')}

                                        /></Pressable >
                                        <View style={{...styles.choosefengmian,  width: this.state.videoWidth*0.75,}}>
                                            <TouchableOpacity
                                                style={styles.leftLogo1}
                                                onPress={this.onPresspre}
                                            >
                                                <Image
                                                    style={styles.imgs1}
                                                    source={require('../../../../../assets/imgs/houtui.png')} />
                                            </TouchableOpacity>
                                            <TouchableOpacity
                                                style={styles.rightLogo1}
                                                onPress={this.onPressnext}
                                            >
                                                <Image
                                                    style={styles.imgs1}
                                                    source={require('../../../../../assets/imgs/qianjin.png')} />
                                            </TouchableOpacity>
                                            {/* <TouchableOpacity onPress={() => { this._onPressButton() }}>
                                                <View style={[styles.images, !this.state.imgindex ? { borderColor: "#CC985D" } : '']}><Text style={{ color: "#fff" }}>不使用封面</Text></View>
                                            </TouchableOpacity> */}

                                            {
                                               
                                                newarrimg.map((item, index) => {
                                                    return (
                                                        <View style={[styles.images, this.state.imgindex == index + 1 ? { borderColor: "#CC985D" } : '']} key={index}>
                                                         
                                                          
                                                            <TouchableOpacity onPress={() => { this._onPressButton(index, item) }} style={{
                                                                justifyContent: "center", alignItems: "center", width: '100%',
                                                                height: 138
                                                            }}>
                                                                   
                                                                {
                                                                    item.mtime == 1 ? (<Text style={{ color: "#fff" }}>不使用封面</Text>) : (
                                                                        <Image
                                                                            style={styles.a1}
                                                                            source={{ uri: `file://${item.path}` }}
                                                                        />
                                                                    )
                                                                }

                                                            </TouchableOpacity>

                                                        </View>
                                                    )
                                                })
                                            }
                                        </View>
                                        <View >
                                            <Pressable onPress={this.onPressFunction} style={{ backgroundColor: "#61AEDD", width: 100,height:30, justifyContent: "center", alignItems: "center", marginTop: 5 }}>
                                                <Text style={{ color: "#fff", fontSize: 15 }} >确定</Text>
                                            </Pressable>
                                        </View>
                                    </ImageBackground>
                                   </View>

                                </Modal>
                            </View>
                        </View>

                        <TouchableHighlight
                            style={{ ...styles.openButton }}
                        // onPress={this.login}
                        >
                            {
                                this.props.importitem ? (<Text style={styles.textStyle} onPress={() => { this.changeexam() }}>{'替换更新'}</Text>) : (<Text style={styles.textStyle} onPress={() => { this.copyexam() }}>{'加入题库'}</Text>)
                            }

                        </TouchableHighlight>
                    </ImageBackground>
                </View>
            </Modal>
        );
    }
}

export default Tikumodel;
const styles = StyleSheet.create({
    // model样式
    shawdows: {
        backgroundColor: 'rgba(0, 0, 0.1, 0.2)',
        padding: 20,
    },
    centeredView: {
        flex: 1,
        justifyContent: "center",
        alignItems: "center",
        marginTop: 22
    },
    modalView: {
        width: 500,
        height: 350,
        margin: 20,
        // backgroundColor: "#3078BB",
        borderRadius: 20,
        padding: 35,
        alignItems: "center",
        shadowColor: "#000",
        shadowOffset: {
            width: 0,
            height: 2
        },
        shadowOpacity: 0.25,
        shadowRadius: 3.84,
        elevation: 5
    },
    modalView1: {
        // flex: 1,
        // flexDirection:"row",
        // justifyContent: "center",
        // alignItems: "center",
        // marginTop: 50,
        // width: 850,
        // height: 400,
        // left: 50,
        // margin: 20,
      
        paddingTop:30,
        paddingBottom:30,
        borderRadius: 20,
        // padding: 20,
        position:'relative',
        // top:-20,
        alignItems: "center",
        shadowColor: "#000",
        shadowOffset: {
            width: 0,
            height: 2
        },
        shadowOpacity: 0.25,
        shadowRadius: 3.84,
        elevation: 5
    },
    leftLogo1: {
        position: "absolute",
        left: -85,
        width: 80,
        height: 80,
        top: 100

    },
    rightLogo1: {
        position: "absolute",
        right: -65,
        width: 80,
        height: 80,
        top: 100


    },
    imgs1: {

        height: 100,
        width: 100
    },
    openButton: {
        backgroundColor: "#CC975D",

        borderRadius: 5,
        padding: 8,
        elevation: 2,
        marginTop: 30,
        width: 100,
        fontSize: 8,
    },
    chooseButton: {
        backgroundColor: "#3070AF",
        borderColor: '#80B3D5',
        borderRadius: 5,
        padding: 10,
        elevation: 2,
        marginTop: 10,
        width: 200,
        fontSize: 8,
        marginBottom: 10,
    },
    fmButton: {
        backgroundColor: "#62AFDD",
        borderRadius: 5,
        padding: 10,
        elevation: 2,
        marginTop: 10,
        width: 100,
        fontSize: 8,
        marginLeft: 50

    },
    textStyle: {
        color: "white",
        fontWeight: "bold",
        textAlign: "center"
    },
    modalText: {
        marginBottom: 15,
        textAlign: "center",
        color: '#fff'
    },
    contaner: {
        flexDirection: 'row',
        justifyContent: 'space-around',
        height: 180

    },
    contanerleft: {
        width: 150,
        marginRight: 50,
        borderWidth: 2,
        borderColor: '#62AFDD',
        shadowColor: "black",
        textAlign: "center",



    },
    tikutitle: {
        textAlign: "center",
        marginTop: 50,

    },
    yikutype: {
        flex: 1,
        justifyContent: "center",
        alignItems: "center",

    },
    contanerright: {
        width: 200,
        // backgroundColor: "red",



    },
    tinyLogo: {
        resizeMode: 'stretch',
        position: 'absolute',
        width: 150,
        height: 180,
        justifyContent: 'space-around',
        alignItems: "center"


    },
    choosefengmian: {
      
        height: 300,
        marginLeft: 50,
        marginRight: 50,
        display: "flex",
        flexDirection: 'row',
        flexWrap: "wrap",
        justifyContent: 'space-around',
        alignItems: "center"

    },
    images: {
        width: '18%',
        height: 140,
        marginTop: 10,
        borderColor: '#78FAF6',
        borderWidth: 2,
        shadowColor: "#78FAF6",
        display: 'flex',
        justifyContent: 'center',
        alignItems: "center"
        // shadowOffset: {
        //     width: 0,
        //     height: 0
        // },
        // shadowOpacity: 0.25,
        // shadowRadius: 3.84,
        // elevation: 5
        // flex:1
    },
    a1: {
        width: '100%',
        height: 138
    }
})
